import cv2
import numpy as np
import pyautogui
import logging
from PIL import Image
import os
import time

class ImageUtils:
    def __init__(self):
        self.logger = logging.getLogger(__name__)

    def find_image_on_screen(self, template_path, confidence=0.8, region=None):
        """在屏幕上查找图像"""
        try:
            if not os.path.exists(template_path):
                raise FileNotFoundError(f"模板图像不存在: {template_path}")

            # 获取屏幕截图
            screenshot = pyautogui.screenshot()
            screenshot = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)

            # 加载模板图像
            template = cv2.imread(template_path)

            if region:
                x, y, w, h = region
                screenshot = screenshot[y:y+h, x:x+w]

            # 执行模板匹配
            result = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED)
            min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

            if max_val >= confidence:
                x, y = max_loc
                w, h = template.shape[1], template.shape[0]
                if region:
                    x += region[0]
                    y += region[1]
                return (x + w//2, y + h//2)  # 返回中心点坐标
            return None

        except Exception as e:
            self.logger.error(f"查找图像失败: {str(e)}")
            return None

    def click_image(self, template_path, confidence=0.8, region=None, duration=0.2):
        """点击找到的图像"""
        try:
            location = self.find_image_on_screen(template_path, confidence, region)
            if location:
                x, y = location
                pyautogui.moveTo(x, y, duration=duration)
                pyautogui.click()
                return True
            return False
        except Exception as e:
            self.logger.error(f"点击图像失败: {str(e)}")
            return False

    def wait_for_image(self, template_path, timeout=10, confidence=0.8, region=None):
        """等待图像出现"""
        try:
            start_time = time.time()
            while time.time() - start_time < timeout:
                if self.find_image_on_screen(template_path, confidence, region):
                    return True
                time.sleep(0.5)
            return False
        except Exception as e:
            self.logger.error(f"等待图像失败: {str(e)}")
            return False

    def save_screenshot(self, save_path, region=None):
        """保存屏幕截图"""
        try:
            screenshot = pyautogui.screenshot(region=region)
            screenshot.save(save_path)
            return True
        except Exception as e:
            self.logger.error(f"保存截图失败: {str(e)}")
            return False

    def get_screen_size(self):
        """获取屏幕尺寸"""
        try:
            return pyautogui.size()
        except Exception as e:
            self.logger.error(f"获取屏幕尺寸失败: {str(e)}")
            return None 